import React, { Component, Fragment } from 'react'
import { Button, Input, Table, Badge, Card, Modal, message } from 'antd'
import { inject, observer } from 'mobx-react/index'
import FileSaver from 'file-saver'

import request from '@/Utils/fecth'
import { address } from '@/Utils/apiConfig'
import Empty from '@/pages/Dashboard/common/Empty/index'
import { PEERNODEJOINCHANNEL } from '@/Utils/socketName'
import Event from '@/Utils/Event'

import './channelOrg.less'

const { leagueManagement: { getChannelOrg }, common: { download }} = address
const { Search } = Input

const STATUS = {
  'CREATING': '创建中',
  'SUCCESS': '成功',
  'FAILED': '失败',
  'Running': '运行中',
}

@inject('BreadCrumb')
@observer
class ChannelOrg extends Component {
  constructor(props) {
    super(props)
    this.state = {
      dataList: [], // 组织列表
      page: 1,
      size: 10,
      loading: true,
      consortiumId: props.match.params.id,
      consortiumName: props.match.params.name,
      channelId: props.match.params.channelId,
      channelName: props.match.params.channelName,
      totalNum: 0,
      leagueInfo: {},
    }
  }

  componentDidMount() {
    this.getChannelOrganization()
    this.getLeagueInfo()
    Event.on(PEERNODEJOINCHANNEL, this.getChannelOrganization)
  }

  componentWillUnmount() {
    Event.off(PEERNODEJOINCHANNEL, this.getChannelOrganization)
  }

  async getLeagueInfo() {
    const { consortiumId } = this.state
    const { status, data } = await request().get(address.leagueManagement.leagueInfo.format({ consortiumId }))
    if (status === 200) {
      this.setState({
        leagueInfo: data || {},
      })
    }
  }

  // 获取组织列表
  getChannelOrganization = async() => {
    const { channelId, page, size } = this.state
    let list = null
    await request().get(getChannelOrg.format(
      { channelId: channelId, pageNum: page, pageSize: size }
    )).then(res => {
      switch (res.status) {
      case 200:
        list = res.data.organizations
        this.setState({
          dataList: list,
          totalNum: res.data.totalNum,
          loading: false,
        })
        this.totalData = list
        break
      default:
        message.error('请求失败')
        break
      }
    })
    return list
  }

  changeTable = (pagination, filters, sorter) => {
    const { current, pageSize } = pagination
    this.setState({
      page: current,
      size: pageSize,
      loading: true,
    }, () => {
      this.getChannelOrganization()
    })
  }

  joinPeer = (record) => {
    const { consortiumId, channelName, channelId, consortiumName } = this.state
    this.props.history.push({
      pathname: `/dashboard/fabric/leagueInfo/${consortiumId}/${consortiumName}/channelOrg/${channelId}/${channelName}/addNode/${record.id}/${record.display_name}`,
      // query: {
      // channelId: channelId,
      // channelName: channelName,
      // consortiumId: consortiumId,
      // peerName: record.name,
      // peerId: record.id,
      // }
    })
  }

  // 渲染表格
  NestedTable = () => {
    const { dataList, page, size, totalNum } = this.state
    // 子表格
    const expandedRowRender = (record) => {
      const nodeList = record.nodes
      const columnsSub = [
        { title: '节点名称', dataIndex: 'name', key: 'name' },
        { title: '节点域名', dataIndex: 'domain', key: 'domain' },
        { title: '访问地址', dataIndex: 'address', key: 'address', width: '25%', render: (v, record) => `grpcs://${record.node_domain}${record.node_port ? ':' + record.node_port : ''}` },
        {
          title: '状态',
          dataIndex: 'status',
          key: 'status',
          className: 'status',
          render: (text) =>
            <div>
              <Badge className={text} status="processing" />
              <span className={text + '-txt'}>{STATUS[text]}</span>
            </div>,
        },
      ]
      return <Table columns={columnsSub} rowKey={record => record.id} dataSource={nodeList} pagination={false}/>
    }

    const columns = [
      { title: '组织名', dataIndex: 'display_name', key: 'display_name', render: (text) => <span>{text || '无'}</span> },
      { title: '节点数', dataIndex: 'nodeNums', key: 'nodeNums' },
      { title: '所属ID', dataIndex: 'id', key: 'id' },
      { title: '组织类型', dataIndex: 'type', key: 'type', width: 132 },
      {
        title: '操作',
        width: '20%',
        dataIndex: '',
        render: (text, record) =>
          <span
            style={{ paddingLeft: 0 }}
            className="common-operation"
            onClick={() => this.joinPeer(record)}
          >
					加入节点
          </span>,
      },
    ]
    const pagination = {
      pageSize: size,
      current: page,
      pageSizeOptions: ['5', '10', '20', '50'],
      simple: false,
      showQuickJumper: true,
      showSizeChanger: true,
      total: totalNum,
    }
    return (
      <Fragment>
        <Table
          className={dataList.length ? 'common-box' : 'common-box empty-list'}
          pagination={pagination}
          onChange={this.changeTable}
          columns={columns}
          rowKey={record => record.id}
          expandable={{ expandedRowRender }}
          dataSource={dataList}
        />
        { dataList.length ? null : <Empty/> }
      </Fragment>
    )
  }

  // 申请添加组织
  goApply = () => {
    const { consortiumId, consortiumName, channelId, channelName } = this.state
    this.props.history.push({
      pathname: `/dashboard/fabric/leagueInfo/${consortiumId}/${consortiumName}/joinChannel/${channelId}/${channelName}/APPLY`,
    })
  }

  inviteOrg = () => {
    const { consortiumId, consortiumName, channelId, channelName } = this.state
    this.props.history.push({
      pathname: `/dashboard/fabric/leagueInfo/${consortiumId}/${consortiumName}/joinChannel/${channelId}/${channelName}/INVITE`,
    })
  }

  // 组织名称模糊查询
  handleSearch = (value) => {
    if (value) {
      const dataList = this.totalData
      const newList = dataList.filter(item => item.name.indexOf(value) >= 0)
      this.setState({
        dataList: newList,
      })
    } else {
      this.setState({
        dataList: this.totalData,
      })
    }
  }

  downloadSdk = async() => {
    Modal.confirm({
      content: '是否确认下载国密SDK到本地?',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        const filename = 'guomi-sdk-2.0.3.zip'
        request().get(download, {
          responseType: 'blob',
          params: {
            filename: encodeURIComponent(filename),
          },
        }).then(res => {
          const status = res.status
          if (status === 200) {
            FileSaver.saveAs(res.data, filename)
          }
        })
      },
    })
  }

  render() {
    // const { leagueInfo } = this.state
    const NestedTable = this.NestedTable
    return (
      <Fragment>
        <Card bordered={false} className="channel-org-box common">
          <Button type="primary" onClick={this.goApply} style={{ marginBottom: 24 }}>申请添加组织</Button>
          {/* {
            !!leagueInfo.isGuomi &&
          <Button type="primary" onClick={this.downloadSdk} style={{ marginBottom: 24, marginLeft: 8 }}>国密SDK下载</Button>
          } */}
          {/* <Button className="com-normal-btn com-btn-secondary" onClick={this.inviteOrg} style={{marginBottom: 24, marginLeft: 8}}>邀请组织</Button> */}
          <Search
            placeholder="请输入组织名"
            onSearch={this.handleSearch}
            style={{ width: 200, marginBottom: 24, float: 'right', borderRadius: 4 }}
          />
          <NestedTable />
        </Card>
      </Fragment>
    )
  }
}

export default ChannelOrg
